package edu.yourl.domain;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.yourl.domain.exception.InvalidDomainInUrlException;
import edu.yourl.domain.service.ServiceLocator;


public class Domain extends Gossiper {

	private static final long serialVersionUID = 1L;

	private static final Pattern DOMAIN_PATTERN = Pattern
	.compile("(https?://)?([\\w!~*'()-]+\\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\\.[a-zA-Z]{2,6}");
	
	protected String domain;
	
	public Domain(String domain) {
		super();
		this.domain = domain;
		this.seoFriendlyId = slugify(getFavoritableName());
	}

	@Override
	public String getFavoritableName() {
		return domain;
	}

	public static Domain extractFromUrl(String url) {
		Matcher matcher = DOMAIN_PATTERN.matcher(url);
		if(matcher.lookingAt()) {
			String domainName = matcher.group();
			Domain domain = ServiceLocator.getInstance().getFavoritableRepository().findFavoritableByName(Domain.class, domainName); 
			if (domain == null) {
				// New domain
				domain = new Domain(domainName);
			}
			return domain;
		} else {
			throw new InvalidDomainInUrlException();
		}
	}
	
	@Override
	public <T> T accept(FavoritableVisitor<T> visitor) {
		return visitor.visit(this);
	}

}
